package com.gitee.form_token.service;

import com.gitee.form_token.common.Const;
import com.gitee.form_token.common.Result;
import com.gitee.form_token.dto.LoginDto;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyRegiterService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private MyUserDetailsService userDetailsService;

    public Result register(LoginDto login) {

        String username = login.getUsername();
        String password = login.getPassword();

        if (username == null || password == null) {
            return Result.fail(Const.loginNullMsg);
        }

        String newPassword = passwordEncoder.encode(password);

        List<GrantedAuthority> authorities = new ArrayList<>();

        UserDetails users = User.builder()
                .username(username)
                .password(newPassword)
                .authorities(authorities)
                .build();

        userDetailsService.createUser(users);

        return Result.success("注册成功");
    }

}
